<template>
  <div>
    <el-table
      ref="multipleTable"
      v-loading="listLoading"
      :header-cell-style="rowClass"
      :data="data"
      :height="tableHeight"
      :max-height="height"
      :highlight-current-row="true"
      :row-key="row_key"
      tooltip-effect="dark"
      :expand-row-keys="expandRowKeys"
      select-on-indeterminate
      border
      stripe
      size="small"
      element-loading-text="加载中..."
      :span-method="spanMethod"
      :cell-style="cellStyle"
      empty-text="暂无数据"
      :row-style="{ height: '34px' }"
      :row-class-name="tableRowClassName"
      :header-row-style="{
        color: '#000',
        height: '34px',
        background: '#EEEEEE'
      }"
      @expand-change="expandChange"
      @select="selectCheck"
      @selection-change="selectChange"
      @row-click="rowClick"
      @row-dblclick="dblclick"
      @filter-change="filterChange"
      @sort-change="sortChange"
      @row-contextmenu="rowContextmenu"
    >
      <!-- :span-method="spanMethod ? spanMethod: false" :selectable="isRowSelectable" -->
      <el-table-column
        v-if="select"
        type="selection"
        width="55"
        :selectable="isRowSelectable"
      />
      <el-table-column
        v-if="showIndex"
        type="index"
        align="center"
        label="序号"
        width="60"
      />
      <el-table-column v-if="expand" type="expand">
        <template slot-scope="scope">
          <el-form label-position="left" inline class="demo-table-expand">
            <el-form-item
              v-for="(item, index) in expandList"
              :key="index"
              :style="{ width: expandList[0].width }"
              :label="item.text"
            >
              <span
                v-html="
                  formatter(
                    scope.row[item.value],
                    item.formatter,
                    scope.row,
                    item.filter,
                    item.filterParams
                  )
                "
              />
            </el-form-item>
          </el-form>
        </template>
      </el-table-column>
      <el-table-column
        v-for="(item, index) in columns"
        v-if="item.type !== 'iconButton' && columns.length > 0"
        :key="index"
        :label="item.text"
        :width="item.width"
        :filter-multiple="item.filterMultiple ? item.filterMultiple : false"
        :prop="item.value"
        :column-key="item.value"
        :align="item.align ? item.align : 'left'"
        :sortable="item.sortable ? 'custom' : null"
        :filters="item.headFilters ? item.headFilters : null"
      >
        <my-column
          v-for="(child, index) in item.children"
          v-if="item.children"
          :key="index"
          :item="child"
        />
        <template slot-scope="scope">
          <my-render
            v-if="item.render"
            :row="scope.row"
            :index="scope.$index"
            :render="item.render"
          />
          <span
            v-if="!item.type"
            :style="item.style ? item.style : ''"
            :class="item.classFun ? item.classFun(scope.row) : ''"
            @click="item.click ? item.click(scope.row, $event) : false"
            v-html="
              formatter(
                scope.row[item.value],
                item.formatter,
                scope.row,
                item.filter,
                item.filterParams
              )
            "
          />
          <img
            v-if="item.type === 'img'"
            :src="item.getSrc(scope.row)"
            :height="item.imgHeight"
          >
          <div v-if="item.type === 'button'">
            <el-button
              v-for="(key, num) in item.list(scope.row)"
              :key="num"
              v-button-privilege="key.privilege"
              size="mini"
              :type="key.type"
              @click="key.click(scope, $event)"
            >{{ key.value }}
            </el-button>
          </div>
          <!--<div v-if="item.type === 'iconButton'">-->
          <!--&lt;!&ndash; <span v-if="item.value"-->
          <!--style="margin-right:5px">{{ scope.row[item.value] }}</span> &ndash;&gt;-->
          <!--<span v-for="(key, num) in dealBtnsByPrivilege(item.list(scope.row))"-->
          <!--:key="num">-->
          <!--&lt;!&ndash;    v-button-privilege="key.privilege" &ndash;&gt;-->
          <!--<el-tooltip :content="key.value"-->
          <!--placement="top">-->
          <!--<i style="font-size: 25px; padding-right: 5px;"-->
          <!--class="icon iconfont projectColor pointer"-->
          <!--:class="key.class"-->
          <!--@click="key.click(scope,$event)" />-->
          <!--</el-tooltip>-->
          <!--&lt;!&ndash;<i v-button-privilege="key.privilege" style="font-size: 25px; padding-right: 5px;" class="icon iconfont projectColor pointer" :class="key.class" @click='key.click(scope,$event)'  ></i>&ndash;&gt;-->
          <!--&lt;!&ndash; item.list(scope.row).length-1 &ndash;&gt;-->
          <!--<span class="projectColor"-->
          <!--style="position: absolute;margin-left: -4px;font-weight: 700;"-->
          <!--v-if="num < dealBtnsByPrivilege(item.list(scope.row)).length-1">|</span>-->
          <!--</span>-->
          <!--</div>-->
          <div v-if="item.type === 'textButton'" class="textButton">
            <el-button
              v-for="(key, num) in dealBtnsByPrivilege(item.list(scope.row))"
              :key="num"
              v-button-privilege="key.privilege"
              class="pointer textSpan"
              :class="{ disabled: key.disabled }"
              :disabled="key.disabled"
              size="mini"
              @click="key.click(scope, $event)"
            >{{ key.value }}
              <span
                v-if="
                  num < dealBtnsByPrivilege(item.list(scope.row)).length - 1
                "
                style="margin: 5px;color: rgba(0,0,0,0.3)"
              >|</span>
            </el-button>
          </div>
          <div v-if="item.type === 'switch'">
            <el-switch
              v-model="scope.row[item.model]"
              :disabled="item.disabled"
              :active-value="item.activeValue"
              :inactive-value="item.inactiveValue"
              :active-text="item.activeText"
              :inactive-text="item.inactiveText"
              @change="item.change(scope, scope.row[item.model])"
            />
          </div>
        </template>
      </el-table-column>
      <el-table-column
        v-for="(item, index) in columns"
        v-if="item.type === 'iconButton' && columns.length > 0"
        :key="index"
        :label="item.text"
        :width="item.width"
        :filter-multiple="item.filterMultiple ? item.filterMultiple : false"
        :prop="item.value"
        :column-key="item.value"
        align="center"
        :sortable="item.sortable ? 'custom' : null"
        :filters="item.headFilters ? item.headFilters : null"
      >
        <my-column
          v-for="(child, index) in item.children"
          v-if="item.children"
          :key="index"
          :item="child"
        />
        <template slot-scope="scope">
          <my-render
            v-if="item.render"
            :row="scope.row"
            :index="scope.$index"
            :render="item.render"
          />
          <div v-if="item.type === 'iconButton'">
            <!-- <span v-if="item.value"
                  style="margin-right:5px">{{ scope.row[item.value] }}</span> -->
            <span
              v-for="(key, num) in dealBtnsByPrivilege(item.list(scope.row))"
              :key="num"
            >
              <!--    v-button-privilege="key.privilege" -->
              <el-tooltip :content="key.value" placement="top">
                <i
                  style="font-size: 25px; padding-right: 5px;"
                  class="icon iconfont projectColor pointer"
                  :class="key.class"
                  @click="key.click(scope, $event)"
                />
              </el-tooltip>
              <!--<i v-button-privilege="key.privilege" style="font-size: 25px; padding-right: 5px;" class="icon iconfont projectColor pointer" :class="key.class" @click='key.click(scope,$event)'  ></i>-->
              <!-- item.list(scope.row).length-1 -->
              <span
                v-if="
                  num < dealBtnsByPrivilege(item.list(scope.row)).length - 1
                "
                class="projectColor"
                style="position: absolute;margin-left: -4px;font-weight: 700;"
              >|</span>
            </span>
          </div>
        </template>
      </el-table-column>
      <el-table-column
        v-if="selectEnd"
        type="selection"
        width="55"
        :selectable="isRowSelectable"
      />
    </el-table>
    <el-pagination
      v-if="showPagination && total >= pageSize"
      ref="pagination"
      style="margin-top: 10px;width: 80%;"
      :current-page="pageNum"
      :page-size="pageSize"
      :small="smallPagination"
      layout="total, prev, pager, next, jumper"
      :total="total"
      @current-change="currentChange"
    />
  </div>
</template>
<script>
import buttonPrivilege from '@/directive/buttonPrivilege'
import myColumn from './myColumn'
import MyRender from './MyRender'
import { mapGetters } from 'vuex'

export default {
  name: 'TableList',
  directives: {
    buttonPrivilege
  },
  components: {
    myColumn,
    MyRender
  },
  props: {
    data: {
      type: Array,
      default: () => {
        return []
      }
    },
    height: {
      type: Number,
      default: () => {
        return
      }
    },
    columns: {
      type: Array,
      default: () => {
        return []
      }
    },
    styleObj: {
      type: Object,
      default: () => {
        return {}
      }
    },
    select: {
      type: Boolean,
      default: () => {
        return false
      }
    },
    selectEnd: {
      type: Boolean,
      default: () => {
        return false
      }
    },
    isAccordion: {
      type: Boolean,
      default: () => {
        return false
      }
    },
    rowkey: {
      type: String,
      default: () => {
        return 'id'
      }
    },
    pageNum: { type: Number, default: 1 },
    pageSize: { type: Number, default: 10 },
    total: { type: Number, default: 0 },
    listLoading: { type: Boolean, default: false },
    showPagination: { type: Boolean, default: true },
    expand: { type: Boolean, default: false },
    showIndex: { type: Boolean, default: false },
    expandList: {
      type: Array,
      default: () => {
        return []
      }
    },
    headColor: { type: String, default: '' },
    spanMethod: {
      type: Function,
      default: () => function() {}
    },
    heightlightRows: {
      type: Array,
      default: () => {
        return []
      }
    },
    myCellStyle: { type: Function, default: null },
    tableHeight: {
      type: Number,
      default: () => {
        return
      }
    },
    tableRowClassName: {
      type: Function,
      default() {
        return () => {}
      }
    },
    // 空间不够 小型分页
    smallPagination: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      expandRowKeys: [],
      oldrowkey: null,
      iconBtnList: []
    }
  },
  computed: {
    ...mapGetters(['projectButtonPrivileges', 'buttonPrivileges'])
  },
  watch: {
    pageNum(val) {
      this.$refs.pagination.lastEmittedPage = val
    }
  },
  mounted() {
    // console.log(this.$refs.multipleTable)
  },
  methods: {
    rowContextmenu(row, colunm, event) {
      event.preventDefault()
      this.$emit('rowContextmenu', row, event)
    },
    filterChange(filters) {
      this.$emit('filterChange', filters)
    },
    sortChange(val) {
      // ascending 表示升序，descending 表示降序，null 表示还原为原始顺序
      this.$emit('sortChange', val)
    },
    selectCheck(selection, row) {
      this.$emit('select', row)
    },
    rowClass({ row, rowIndex }) {
      // console.log(rowIndex)
      return 'background:' + this.headColor
    },
    selectChange(e) {
      this.$emit('selectChange', e)
    },
    rowClick(e) {
      this.$emit('rowClick', e)
    },
    clear() {
      this.$refs.multipleTable.clearSelection()
      return true
    },
    addSerch(rows) {
      rows.forEach(row => {
        this.$refs.multipleTable.toggleRowSelection(row)
      })
    },
    setSelection(rows, value = true) {
      rows.forEach(row => {
        this.$refs.multipleTable.toggleRowSelection(row, value)
      })
    },
    dblclick(e) {
      // 双击表格触发事件
      this.$emit('dbclick', e)
    },
    formatter(value, formatter, row, filter, filterParams) {
      if (!formatter) {
        if (filter) {
          if (filterParams) {
            const tempArr = [value, ...filterParams]
            return filter(...tempArr)
          } else {
            return filter(value)
          }
        }
        return value
      } else {
        return formatter(row)
      }
    },
    highlight(row) {
      this.$refs.multipleTable.setCurrentRow(row)
    },
    currentChange(val) {
      this.$emit('currentChange', val)
    },
    // row 中有{row, column, rowIndex, columnIndex}
    cellStyle(row) {
      if (this.myCellStyle) {
        return this.myCellStyle(row)
      }
    },
    row_key(row) {
      return row[this.rowkey]
    },
    expandChange(e) {
      this.$emit('expandChange', e)
      if (this.isAccordion) {
        if (
          this.oldrowkey === e[this.rowkey] &&
          this.expandRowKeys.length !== 0
        ) {
          this.expandRowKeys = []
        } else {
          this.expandRowKeys = [e[this.rowkey]]
        }
      }
      this.oldrowkey = e[this.rowkey]
    },
    /** *
     * 解决问题  如果是有权限时 利用指令的话  最后一条竖线是始终存在的
     * 解决方案 将有权限的按钮提前筛选出来
     * by zhujun
     */
    dealBtnsByPrivilege(btnList) {
      let iconBtnList = []
      const projectButtonPrivileges = this.$store.getters
        .projectButtonPrivileges || []
      const buttonPrivileges = this.$store.getters.buttonPrivileges || []
      const privileges = [...projectButtonPrivileges, ...buttonPrivileges]
      iconBtnList = btnList.filter(item => {
        return !item.privilege || privileges.indexOf(item.privilege) !== -1
      })
      return iconBtnList
    },
    // 判断行是否可选
    isRowSelectable(row) {
      return !!row.selectable
    }
  }
}
</script>
<!-- table测试组件 -->
<style rel="stylesheet/scss" lang="scss">
.el-table {
  border: 0px;
}
.el-table th,
.el-table tr {
  background: rgba(0, 0, 0, 0);
}

.el-table--border td,
.el-table--border th {
  border: 0px;
  border-bottom: 1px solid rgba(0, 0, 0, 0.1);
}

.el-table--striped .el-table__body tr.el-table__row--striped td {
  background: #fafcfb;
}

.el-table__header-wrapper {
  /*border-top-left-radius: 13px;*/
  /*border-top-right-radius: 13px;*/
  background: #edf7ff;
}

.el-table::before {
  height: 0px;
}

.el-table--border::after,
.el-table--group::after {
  width: 0px;
}

.demo-table-expand {
  font-size: 0;
}

.demo-table-expand label {
  color: #99a9bf;
}

.demo-table-expand .el-form-item {
  margin-right: 0;
  margin-bottom: 0;
}
.textButton {
  .textSpan {
    color: #05c1fa;
    &:hover {
      color: #0490ba;
    }
    border: 0px;
    background: rgba(0, 0, 0, 0);
    padding: 0px;
    margin: 0px;
    &.disabled {
      color: #ccc;
    }
  }
}
/*.el-table td.is-center{*/
/*text-align: left;*/
/*}*/
</style>
